
#include "simmodel.h"
#include "varSelection.h"
#include "ui_varSelection.h"
#include <QtGui/QWidget>
#include <QTextCodec>
#include <QMessageBox>
#include <vector>

using namespace std;

varSelection::varSelection(QWidget* pwgt) 
	: QDialog(pwgt, Qt::WindowTitleHint | Qt::WindowSystemMenuHint)
{
	ui.setupUi(this);
	connect(ui.bAccept, SIGNAL(clicked), this, SLOT(on_bAccept_clicked()));
	connect(ui.bReject, SIGNAL(clicked), this, SLOT(on_bReject_clicked()));
	connect(ui.bCheckAll, SIGNAL(clicked), this, SLOT(on_bCheckAll_clicked()));

}

varSelection::~varSelection(){

}

void varSelection::on_bAccept_clicked(){
	accept();
}

void varSelection::on_bReject_clicked(){
	reject();
}

void varSelection::on_bCheckAll_clicked(){
	for (int i = 0; i < ui.tableWidget->rowCount(); i++)
		ui.tableWidget->item(i, 0)->setCheckState(Qt::Checked);
}

vector<string> varSelection::getSetOfUnits(string u){
	pair<vector<vector<string>>, vector<vector<double>>> p = VectorUnitAndCoeff;
	for (unsigned int i = 0; i < p.first.size(); ++i)
		if(std::find(p.first[i].begin(), p.first[i].end(), u) != p.first[i].end()) return p.first[i];
	QMessageBox::critical(this, "Error", "Unit not found.", QMessageBox::Ok);
	vector<string> n;
	return n;
}

void varSelection::setData(string _typePlot, vector<vector<string>> data, pair<vector<vector<string>>, vector<vector<double>>> unitAndCoeff){
	typePlot = _typePlot;
	VectorUnitAndCoeff = unitAndCoeff;
	ui.tableWidget->setRowCount(data.size());
	ui.tableWidget->setColumnWidth(0, 20);
	ui.tableWidget->setColumnWidth(1, 140);
	for (unsigned int i = 0; i < data.size(); i++){
		//display Check
		QTableWidgetItem *itemCheck = new QTableWidgetItem;
		itemCheck->setCheckState(Qt::Unchecked);
		ui.tableWidget->setItem(i,0,itemCheck);
		//display Property
		QTableWidgetItem *itemName = new QTableWidgetItem;
		itemName->setText(QString::fromStdString(data[i][0]));
		itemName->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
		ui.tableWidget->setItem(i,1,itemName);
		//display Value
		QComboBox *itemUnit = new QComboBox;
		vector<string> units = getSetOfUnits(data[i][1]);
		for (unsigned int j = 0; j < units.size(); j++)
			itemUnit->addItem(QString::fromStdString(units[j]));
		ui.tableWidget->setCellWidget(i, 2, itemUnit);
	}
}

pair<vector<string>, vector<string>> varSelection::getData(){
	vector<string> parameter, unit;
	for (unsigned int i = 0; i < ui.tableWidget->rowCount(); i++)
		if (ui.tableWidget->item(i, 0)->checkState() == Qt::Checked){
			//display Property
			parameter.push_back(ui.tableWidget->item(i, 1)->text().toStdString());
			//display Value
			QComboBox *itemUnit = qobject_cast<QComboBox*>(ui.tableWidget->cellWidget(i, 2));
			unit.push_back(itemUnit->currentText().toStdString());
		}

	return make_pair(parameter, unit);
}

string varSelection::getTypePlot(){
	return typePlot;
}